package com.lanf.generator;

/**
 * @author tanlingfei
 * @version 1.0
 * @description TODO
 * @date 2023/5/30 14:55
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Set;

public class JsonUtil {

    public static void convert(Object obj) {
        if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) obj;
            for (Object json : jsonArray) {
                convert(json);
            }
        } else if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            Set<String> keySet = json.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            for (String key : keyArray) {
                Object value = json.get(key);
                String[] keyStrs = key.split("_");
                if (keyStrs.length > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < keyStrs.length; i++) {
                        String keyStr = keyStrs[i];
                        if (!keyStr.isEmpty()) {
                            if (i == 0) {
                                sb.append(keyStr);
                            } else {
                                int c = keyStr.charAt(0);
                                if (c >= 97 && c <= 122) {
                                    int v = c - 32;
                                    sb.append((char) v);
                                    if (keyStr.length() > 1) {
                                        sb.append(keyStr.substring(1));
                                    }
                                } else {
                                    sb.append(keyStr);
                                }
                            }
                        }
                    }
                    json.remove(key);
                    json.put(sb.toString(), value);
                }
                convert(value);
            }
        }
    }

    /**
     * 将json字符串中的key名称中包含下划线的字段，转成驼峰命名格式
     *
     * @param str String格式的JSON串
     * @return 转换后的对象（可能是JSONObject或JSONArray）
     */
    public static Object convertUnderlineToCamelCase(String str) {
        Object obj = JSON.parse(str);
        convert(obj);
        return obj;
    }

    public static void main(String[] args) {
        String json = "{\n" +
                "  \"test\": [\n" +
                "    {\n" +
                "      \"self_auth\": {\n" +
                "        \"a_id\": \"123\",\n" +
                "        \"b_num\": 7,\n" +
                "        \"user_name\": \"oldlu\"\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        String str = "" + convertUnderlineToCamelCase(json);
        System.out.println(str);
    }
}

